package com.dapeis.api.utils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ag.core.exception.SignException;
import com.ag.core.utils.AgAssert;
import com.ag.utils.AlgorithmEnum;
import com.ag.utils.AlgorithmUtils;
import com.ag.utils.DictionarySettingUtils;
import com.ag.web.controller.BaseController;
import com.dapeis.exception.api.VersionToLowException;

public class ApiSignUtils {
    protected final static Logger logger = LoggerFactory
	    .getLogger(ApiSignUtils.class);
    public static final String signKey = "a5063dce1b2d2013de0b9f40cb25c5c1";

    public static void checkSign(HttpServletRequest request, String apiName,
	    String signKey) {
	BaseController.printHeader(request);
	String requestURI = request.getRequestURI();

	if (StringUtils.indexOf(requestURI, "/common/") > -1) {
	    return;
	}

	String id = null;
	if (StringUtils.indexOf(requestURI, "/collocation/") > -1) {
	    id = request.getHeader("collocationId");
	} else {
	    id = request.getHeader("userId");
	    if (StringUtils.isBlank(id)) {
		id = request.getHeader("collocationId");
	    }
	}

	checkXdmApiSign(request, apiName, id, signKey);
    }

    @SuppressWarnings("rawtypes")
    public static void checkXdmApiSign(HttpServletRequest request,
	    String apiName, String id, String signKey) {
	String isOpenDebug = DictionarySettingUtils
		.getParameterValueWithDefault("cfg.rest.debug", "1");
	boolean isOpenDebugFlag = "1".equals(isOpenDebug);
	String debug = request.getParameter("debug");
	debug = debug == null ? request.getHeader("debug") : debug;
	if (isOpenDebugFlag && "1".equals(debug)) {
	    return;
	}

	String switchSign = DictionarySettingUtils
		.getParameterValueWithDefault("switch.checkSign." + apiName,
			"1");
	if (isOpenDebugFlag && !"1".equals(switchSign)) {
	    return;
	}

	if (id == null) {
	    id = "";
	}

	Map<String, String> params = new HashMap<String, String>();
	Map requestParams = request.getParameterMap();
	for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
	    String name = (String) iter.next();
	    String[] values = (String[]) requestParams.get(name);
	    String valueStr = "";
	    for (int i = 0; i < values.length; i++) {
		valueStr = (i == values.length - 1) ? valueStr + values[i]
			: valueStr + values[i] + ",";
	    }
	    // 乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
	    // valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
	    params.put(name, valueStr);
	}

	String sign = StringUtils.chomp(params.get("sign"));
	// 没有这个指说明版本过低了
	AgAssert.hasText(sign, VersionToLowException.class);
	// 加密
	Map<String, String> paraFilter = AlipayCore.paraFilter(params);
	String beforeSignStr = AlipayCore.createLinkString(paraFilter);
	beforeSignStr += id + signKey;
	String encode = AlgorithmUtils.encode(beforeSignStr, AlgorithmEnum.MD5);

	if (!sign.equals(encode)) {
	    logger.info("签名前的串:" + beforeSignStr);
	    logger.info("签名后的值:" + encode);
	    throw new SignException();
	}

	logger.debug("sign验证成功.");
    }
}
